<template>
  <div class="" style="margin: 10px auto;width: 600px;">
    <a class="backButton" @click="$router.back()"> ◀ back</a>
    <el-upload
      class="avatar-uploader"
      :action="actionUrl"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
<!--    <el-form>-->
<!--      <el-form-item label="名称">-->
<!--        <el-input></el-input>-->
<!--      </el-form-item>-->
<!--    </el-form>-->
  </div>
</template>

<script>


export default {
  name: 'UserInfoEdit',
  data() {
    return {
      imageUrl: '',
      actionUrl:process.env.VUE_APP_BASE_API + '/user/saveAvatar?id=' + this.$store.state.user.id
    };
  },
  beforeMount() {
    this.imageUrl = this.$store.getters.avatar
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.$store.commit('user/SET_AVATAR', this.imageUrl)
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    }
  }
}
</script>

<style scoped>
.avatar-uploader{
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  margin: 0 auto;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.backButton {
  color: #8c939d;
}
.backButton:hover {
  color: #20a0ff;
}
</style>
